<template>
  <div class="udp-uart-config-container">
    <el-row :gutter="20">
      <!-- Left Side: UDP to uart Configuration -->
      <el-col :span="14">
        <!-- <el-card class="udp-config-card"> -->
        <el-form ref="udpForm" :model="udpConfig" :rules="udpRules" size="mini" label-width="150px">
          <div class="table-container">
            <div class="udp-config-header">
              UDP 转串口配置
              <el-button type="primary" icon="el-icon-plus" class="header-button" size="mini" @click="addUdpConfigRow"></el-button>
            </div>
            <el-table :data="udpConfig.udp2uart" :height="tableHeight" border size="mini" fit>
              <el-table-column type="index" align="center" label="序号" width="80px"></el-table-column>
              <el-table-column label="远端发送端口">
                <template slot-scope="scope">
                  <el-form-item :prop="'udp2uart.' + scope.$index + '.remotePort'" :rules="udpRules.remotePort" label-width="0">
                    <el-input v-model.number="scope.row.remotePort" clearable @clear="clearRemotePort(scope.$index)"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="本地接收端口">
                <template slot-scope="scope">
                  <el-form-item :prop="'udp2uart.' + scope.$index + '.udpPort'" :rules="udpRules.udpPort" label-width="0">
                    <el-input v-model.number="scope.row.udpPort" clearable @clear="clearudpPort(scope.$index)"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="串口输出">
                <template slot-scope="scope">
                  <el-form-item :prop="'udp2uart.' + scope.$index + '.uartId'" :rules="udpRules.uartId" label-width="0">
                    <el-select v-model="scope.row.uartId" placeholder="请选择">
                      <el-option v-for="(port, index) in uartPorts" :key="index" :label="port.label" :value="port.value"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="转发使能" width="110px" align="center">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.enable" :true-label="1" :false-label="0"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="140px" align="center">
                <template slot-scope="scope">
                  <el-button type="danger" size="mini" @click="removeUdpConfigRow(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
        <!-- </el-card> -->
      </el-col>

      <!-- Right Side: Multicast Address Configuration -->
      <el-col :span="10">
        <!-- <el-card class="multicast-config-card"> -->
        <el-form ref="multicastForm" :model="multicastConfig" :rules="multicastRules" size="mini" label-width="150px">
          <div class="table-container">
            <div class="multicast-config-header">
              组播地址配置
              <el-button type="primary" icon="el-icon-plus" class="header-button" size="mini" @click="addMulticastRow"></el-button>
            </div>
            <el-table :data="multicastConfig.multicast" border :height="tableHeight" style="width: 100%;" size="mini" fit>
              <el-table-column type="index" align="center" label="序号" width="80px"></el-table-column>
              <el-table-column label="组播接收地址">
                <template slot-scope="scope">
                  <el-form-item :prop="'multicast.' + scope.$index + '.srcIp'" :rules="multicastRules.srcIp" label-width="0">
                    <el-input v-model="scope.row.srcIp" clearable style="width: 100%;" @clear="clearMulticastAddress(scope.$index)"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="140px">
                <template slot-scope="scope">
                  <el-button type="danger" size="mini" @click="removeMulticastRow(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
        <!-- </el-card> -->
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    var validateUdpPort = (rule, value, callback) => {
      const udpPortPattern = /^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/
      if (value === undefined || value === null || value.toString().trim() === '') {
        callback(new Error('UDP端口不能为空'))
      } else if (udpPortPattern.test(value)) {
        callback()
      } else {
        callback(new Error('端口号范围应在0到65535之间'))
      }
    }

    var validateMulticastAddress = (rule, value, callback) => {
      const multicastPattern = /^(22[4-9]|23[0-9])\.(25[0-5]|2[0-4]\d|1\d\d|\d?\d)\.(25[0-5]|2[0-4]\d|1\d\d|\d?\d)\.(25[0-5]|2[0-4]\d|1\d\d|\d?\d)$/
      // const multicastPattern = /^(22[4-9]|23[0-9])\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
      if (value === undefined || value === null || value.trim() === '') {
        callback(new Error('组播地址不能为空'))
      } else if (value === '0.0.0.0') {
        callback()
      } else if (value === '224.8.8.8') {
        callback(new Error('该地址为YH-hd016配置管理地址，不能使用'))
      } else if (multicastPattern.test(value)) {
        callback()
      } else {
        callback(new Error('无效，组播地址范围应在224.0.0.0到239.255.255.255之间'))
      }
    }

    return {
      // udpConfig: {
      //   udp2uart: []
      // },
      // multicastConfig: {
      //   multicast: []
      // },
      tableHeight: 'calc(100vh - 270px)',
      udpRules: {
        remotePort: [
          { required: true, message: '请输入远程端口', trigger: 'blur' },
          { validator: validateUdpPort, trigger: 'blur' }],
        udpPort: [
          { required: true, message: '请输入本地端口', trigger: 'blur' },
          { validator: validateUdpPort, trigger: 'blur' }],
        uartId: [
          { required: true, message: '请选择串口', trigger: 'change' }
        ]
      },
      multicastRules: {
        srcIp: [
          { required: true, message: '请输入组播地址', trigger: 'blur' },
          { validator: validateMulticastAddress, trigger: 'blur' }]
      },
      uartPorts: Array.from({ length: 16 }, (_, i) => ({
        label: `串口-S${i + 1}`,
        value: i + 1
      }))
    }
  },
  computed: {
    ...mapGetters(['SysCfgInfo']),
    udpConfig() {
      return this.SysCfgInfo.udp2uartRule
    },
    multicastConfig() {
      return this.SysCfgInfo.udp2uartRule
    }
  },
  methods: {
    addUdpConfigRow() {
      this.udpConfig.udp2uart.push({
        remotePort: '',
        udpPort: '',
        uartId: '',
        enable: false
      })
      this.$nextTick(() => this.$refs.udpForm.clearValidate())
    },
    removeUdpConfigRow(index) {
      this.udpConfig.udp2uart.splice(index, 1)
      this.$nextTick(() => this.$refs.udpForm.clearValidate())
    },
    addMulticastRow() {
      this.multicastConfig.multicast.push({
        srcIp: ''
      })
      this.$nextTick(() => this.$refs.multicastForm.clearValidate())
    },
    removeMulticastRow(index) {
      this.multicastConfig.multicast.splice(index, 1)
      this.$nextTick(() => this.$refs.multicastForm.clearValidate())
    },
    clearMulticastAddress(index) {
      this.$refs.multicastForm.validateField('multicast.' + index + '.srcIp')
    },
    clearudpPort(index) {
      this.$refs.udpForm.validateField('udp2uart.' + index + '.udpPort')
    },
    clearRemotePort(index) {
      this.$refs.udpForm.validateField('udp2uart.' + index + '.remotePort')
    },
    save() {
      return new Promise((resolve, reject) => {
        return this.$refs.udpForm.validate((valid) => {
          if (valid) {
            this.$refs.multicastForm.validate((valid) => {
              if (valid) {
                resolve(true)
              } else {
                this.$message.warning('以太网转串口标签页组播地址配置表单校验失败')
                resolve(false)
              }
            })
          } else {
            this.$message.warning('以太网转串口标签页UDP表单校验失败')
            resolve(false)
          }
        })
      })
    },
    getSettings() {
      this.$nextTick(() => this.$refs.udpForm.clearValidate())
      this.$nextTick(() => this.$refs.multicastForm.clearValidate())
    },
    getSysCfg(flag = 0) {
      this.loading = true
      this.$store.dispatch('device/getSysCfg').then(res => {
        this.loading = false
        this.udpConfig.udp2uart = res.udp2uartRule.udp2uart
        this.multicastConfig.multicast = res.udp2uartRule.multicast

        this.$nextTick(() => this.$refs.udpForm.clearValidate())
        this.$nextTick(() => this.$refs.multicastForm.clearValidate())
        if (flag === 1) {
          this.$message.success('以太网转串口配置获取成功')
        }
      }).catch(() => {
        this.loading = false
      })
    }

  }
}
</script>
<style lang="scss" scoped>
.udp-uart-config-container {
  .table-container {
    overflow: auto;
  }

  .header-button {
    float: right;
  }

  .udp-config-header,
  .multicast-config-header {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 25px;
  }
}
</style>
